import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ICOPServer {
	static final ByteBuffer helloRequest = ByteBuffer.wrap("GET /hello.htm"
			.getBytes());	
	public static void main(String args[]) throws Exception {
		ExecutorService executorService = 
			Executors.newCachedThreadPool(Executors.defaultThreadFactory());
		AsynchronousChannelGroup threadGroup =
	        AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);

		final AsynchronousServerSocketChannel server =
	        AsynchronousServerSocketChannel.open(threadGroup);

		server.bind(new InetSocketAddress(8081));
		System.out.println("ICOPServerr start...");
		System.out.println(Runtime.getRuntime().availableProcessors());
		server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
	        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
	        byte[] request = new byte[14];	
	        @Override
	        public void completed(AsynchronousSocketChannel result, Void attachment) {
	        	server.accept(null, this);
	        	try {
	        		readBuffer.clear();
	                result.read(readBuffer).get();
	                readBuffer.position(0);
	                readBuffer.get(request, 0, 14);
	                if (ByteBuffer.wrap(request, 0, 14).compareTo(helloRequest) == 0) {
	                  result.write(ByteBuffer.wrap(("HTTP/1.1 200 OK\n"
	                      + "Content-Type: text/html; charset=utf-8\n"
	                      + "Content-Length: 20\n\n"
	                      + "<h1>HELLO WORLD</h1>"
	                      ).getBytes()));
	                  result.close();
	                }
	        	}
	        	catch (Exception e) {
	        		System.out.println(e.toString());
	        	}
	        }
	
	        @Override
	        public void failed(Throwable exc, Void attachment) {
	        	 throw new UnsupportedOperationException("Not supported yet.");
	        }
	    });


	    // Wait
	    System.in.read();
	
	    server.close();
	}
}